package com.zzyl.nursing.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.dto.AlertDataDTO;
import com.zzyl.nursing.dto.HandleAlertDataDTO;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.INursingElderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 *
 * @author mr.wu
 * @date 2025-05-29
 */
@Slf4j
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }


    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

@Autowired
private INursingElderService  nursingElderService;
    /**
     * 分页查询报警数据列表
     *
     * @param alertDataDTO
     * @return
     */
    @Override
    public Page<AlertData> pageQueryList(AlertDataDTO alertDataDTO) {
        Page<AlertData> page = new Page<>(alertDataDTO.getPageNum(), alertDataDTO.getPageSize());

        Long userId = SecurityUtils.getLoginUser().getUserId();

        // 构建查询条件
        Page<AlertData> pageResult = this.lambdaQuery()
                .eq(alertDataDTO.getStatus() != null, AlertData::getStatus, alertDataDTO.getStatus())
                .like(StringUtils.isNotBlank(alertDataDTO.getDeviceName()),
                        AlertData::getDeviceName, alertDataDTO.getDeviceName())
                .between(alertDataDTO.getStartTime() != null && alertDataDTO.getEndTime() != null,
                        AlertData::getCreateTime, alertDataDTO.getStartTime(), alertDataDTO.getEndTime())
                .eq(alertDataDTO.getId() != null, AlertData::getId, alertDataDTO.getId())
                .eq(!SecurityUtils.isAdmin(userId), AlertData::getUserId, userId) // 非管理员时加条件
                .orderByDesc(AlertData::getCreateTime)
                .page(page);

        return pageResult;
    }


//    @Override
//    public Page<AlertData> pageQueryList(AlertDataDTO alertDataDTO) {
//        Long userId = SecurityUtils.getLoginUser().getUserId();
//        Page<AlertData> page = new Page<>(alertDataDTO.getPageNum(), alertDataDTO.getPageSize());
//        Page<AlertData> page1 = this.lambdaQuery()
//                .eq(alertDataDTO.getStatus() != null, AlertData::getStatus, alertDataDTO.getStatus())
//                .like(StringUtils.isNotBlank(alertDataDTO.getDeviceName()),
//                        AlertData::getDeviceName, alertDataDTO.getDeviceName())
//                .between(alertDataDTO.getStartTime() != null && alertDataDTO.getEndTime() != null,
//                        AlertData::getCreateTime, alertDataDTO.getStartTime(), alertDataDTO.getEndTime())
//                .eq(alertDataDTO.getId() != null, AlertData::getId, alertDataDTO.getId())
//                .orderByDesc(AlertData::getCreateTime)
//                .page(page);
//        if (SecurityUtils.isAdmin(userId)){
//            return page1;
//        }
//        //获取登录用户护理的老人
//        List<NursingElder> list = nursingElderService.lambdaQuery().eq(NursingElder::getNursingId, userId).list();
//        List<Long> elemIds = list.stream().map(nursingElder -> nursingElder.getElderId()).collect(Collectors.toList());
//        if (!CollectionUtils.isEmpty(elemIds)){
//
//        }
//
//    }


    /**
     * 处理设备报警数据
     *
     * @param handleAlertDataDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleAlertData(HandleAlertDataDTO handleAlertDataDTO) {
        //首先先查询当前登录 用户通过本地线程变量
        Long userId = SecurityUtils.getLoginUser().getUserId();
        log.info("当前登录的用户id：{}", userId);
        String username = SecurityUtils.getLoginUser().getUsername();
        log.info("当前登录的用户名：{}", username);
        boolean update = this.lambdaUpdate()
                .eq(AlertData::getId, handleAlertDataDTO.getId())
                .set(AlertData::getStatus, 1)
                .set(AlertData::getProcessingResult, handleAlertDataDTO.getProcessingResult())
                .set(AlertData::getProcessingTime, handleAlertDataDTO.getProcessingTime())
                .set(AlertData::getProcessorId, userId)
                .set(AlertData::getProcessorName, username)
                .set(AlertData::getUpdateBy, userId)
                .set(AlertData::getUpdateTime, LocalDateTime.now())
                .update();
        if (!update) {
            throw new BaseException("更新数据失败");
        }
    }
}
